﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
//using Autofac;
using MyTime.Core.Entities;
using MyTime.ProviderFactory;
using MyTime.ProviderFactory.Entities;

//using SqlCompactProvider;

namespace MyTime.SqlCompactProvider
{
    public class Service : MyTimeProviderBase
    {
        //private readonly ContainerBuilder _builder = new ContainerBuilder();

        public override string Name
        {
            get
            {
                return "SqlCompactProvider";
            }
        }
        public override void Initialize(string name, NameValueCollection config)
        {
            //_builder.RegisterType<ITimeItem>();
        }

        public override void AddTask(ITimeItem timeItem)
        {
            if (timeItem == null)
                throw new ArgumentNullException("timeItem");
            timeItem.Current = true;

            EndLastTask();
            var defaultTimeItem = timeItem as DefaultTimeItem;

            var db = new Context();
            db.SqlTimeItems.Add(defaultTimeItem);
            db.SaveChanges();
        }

        private static void EndLastTask()
        {
            var context = new Context();
            var lastTask = context.SqlTimeItems.FirstOrDefault(task => task.Current);
            if (lastTask == null || lastTask.EndTime.HasValue)
                return;

            var closingTime = DateTime.Now;
            if (lastTask.StartTime != DateTime.Today)
            {
                var remainingTimeInDay =  lastTask.StartTime + new TimeSpan(17, 0, 0);
                closingTime = remainingTimeInDay;
            }

            lastTask.EndTime = closingTime;
            lastTask.TotalTime = (closingTime.Subtract(lastTask.StartTime));
            context.SaveChanges();
        }

        public override IEnumerable<ITimeItem> GetAllTime()
        {
            var context = new Context();
            return context.SqlTimeItems.ToList();
        }

        public override IEnumerable<ITimeItem> GetTodaysTimeItems()
        {
            var context = new Context();
            var todaysTasks = context.SqlTimeItems.Where(task => task.StartTime.Date == DateTime.Now.Date).ToList();
            context.Dispose();
            return todaysTasks;
        }

        public override bool ImportOldData(double version, params string[] param)
        {
            throw new NotImplementedException();
        }

        public override ITimeItem GetCurrentTimeItem()
        {
            var context = new Context();
            var lastTask =
                context.SqlTimeItems.OrderBy(task => task.WeekNumber).ThenBy(task => task.StartTime).Last();
            context.Dispose();
            return lastTask;
        }
    }
}